import {Component, OnInit} from '@angular/core';
import {BladeContainerBase} from '../../../../shared/blade/blade-container-base';
import {Phase} from '../../../../entity/phase.model';
import {PhaseService} from '../../../../service/phase.service';
import {Command} from '../../../../shared/toolbar.service';
import {Observable} from 'rxjs/Observable';
import {Blade} from '../../../../shared/blade/blade.model';
import {BladeData} from '../../../../shared/blade/blade-data';
import {PhaseEditComponent} from '../phase-edit/phase-edit.component';
import {DialogResult} from '../../../../shared/dialog.service';
import {Farm} from '../../../../entity/farm.model';
import {CircuitListComponent} from '../../circuit/circuit-list/circuit-list.component';
import {DeviceListComponent} from '../../device/device-list/device-list.component';
import {CalculateExpressionListComponent} from '../../calculate-expression/calculate-expression-list/calculate-expression-list.component';


@Component({
  selector: 'app-phase-list',
  templateUrl: './phase-list.component.html',
  styleUrls: ['./phase-list.component.css']
})
export class PhaseListComponent extends BladeContainerBase<Phase> {
  phases: Phase[] = [];
  original: Phase[] = [];

  constructor(private phaseService: PhaseService) {
    super();
  }

  ngOnInit(): void {
    this.commands = [
      new Command('add', '添加', 'fa fa-plus', 'setofkey:insert', blade => this.exeAdd(blade), blade => this.canExeAdd(blade)),
      new Command('edit', '编辑', 'fa fa-edit', 'setofkey:update', blade => this.exeEdit(blade), blade => this.canExeEdit(blade)),
      new Command('delete', '删除', 'fa fa-trash-o', 'setofkey:delete', blade => this.exeDelete(blade), blade => this.canDelete(blade)),
      new Command('circuit', '线路', 'fa fa-barcode', 'setofkey:circuit', blade => this.exeCircuitList(blade), blade => this.canCircircuitList(blade)),
      //new Command("station-tag", "电量公式", "fa fa-dot-circle-o", "setofkey:station-tag", blade => this.exeExpressionList(blade), blade => this.canExeEdit(blade)),
    ];
    super.ngOnInit();
    // this.parentEntity
    // console.log("phase-list-"+this.parentEntity.farmId)
  }

  /**
   * 初始化数据
   *
   *
   * @memberof PhaseListComponent
   */
  initData(): any | Observable<any> | Promise<any> {
    if (this.parentEntity === null) {
      this.phaseService.getPhases()
        .then(res => {
          if (res) {
            this.original = [...res];
          }
          this.phases = [...this.original];
          if (this.phases.length > 0) {
            this.currentEntity = this.phases[0];
            this.onSeletedChange(this.currentEntity)
          }
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    } else {
      this.phaseService.getPhasesByfarmId((this.parentEntity as Farm).farmId)
        .then(res => {
          if (res) {
            this.original = [...res];
          }
          ;
          this.phases = [...this.original];
          this.phases.forEach(phase => {
            phase.farmCategory = this.parentEntity.farmCategory;
          })
          if (this.phases.length > 0) {
            this.currentEntity = this.phases[0];
            this.onSeletedChange(this.currentEntity)
          }
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }
  }

  exeAdd(blend: Blade): void {
    let data: BladeData = new BladeData();
    data.id = 'phaseEdit';
    data.title = '新建分期';
    data.isClosingDisabled = false;
    let createKeyBlade = this.bladeService.createBlade(PhaseEditComponent, data, true, null, this.currentEntity);
    this.bladeService.showBlade(createKeyBlade, this.currentBlade);
  }

  canExeAdd(blend: Blade): boolean {
    return true;
  }

  exeEdit(blend: Blade): void {
    if (this.currentEntity != undefined) {
      let data: BladeData = new BladeData();
      data.id = 'phaseEdit';
      data.title = this.currentEntity.phaseName;
      let editKeyBlade = this.bladeService.createBlade(PhaseEditComponent, data, false, this.currentEntity);
      this.currentBlade.bladeService.showBlade(editKeyBlade, this.currentBlade);
    }
  }

  canExeEdit(blend?: Blade): boolean {
    return this.currentEntity != null;
  }

  exeDelete(blend: Blade): void {
    let selectedKeys = this.getSelected();
    if (selectedKeys.length > 0) {
      this.dialogService
        .showConfirmationDialog('确认删除', '是否要删除选中项？')
        .subscribe(dialogResult => {
          if (dialogResult == DialogResult.Ok) {
            this.currentBlade.bladeData.isLoading = true;
            this.phaseService.batchDelete(selectedKeys.map(o => o.phaseId))
              .then(res => {
                if (res) {
                  this.refresh(undefined);
                }
              })
              .catch(error => this.bladeData.error = error)
              .then(res => this.bladeData.isLoading = false);
          }
        })

    }

  }

  canDelete(blend?: Blade): boolean {
    return this.getSelected().length > 0;
  }

  //工期对应线路信息组件（工期查找线路接口）
  exeCircuitList(blend: Blade): void {
    if (this.currentEntity != undefined) {
      let data: BladeData = new BladeData();
      data.id = 'showPhaseCircircuitList';
      data.title = this.currentEntity.phaseName + '线路列表';
      data.isClosingDisabled = false;
      let showPhaseCircircuitList = this.bladeService.createBlade(CircuitListComponent, data, false, null, this.currentEntity);
      this.bladeService.showBlade(showPhaseCircircuitList, this.currentBlade);
    }
  }

  canCircircuitList(blend?: Blade): boolean {
    return this.currentEntity != null;
  }

  //风场对应电量表达式
  exeExpressionList(blend: Blade): void {
    if (this.currentEntity != undefined) {
      let data: BladeData = new BladeData();
      data.id = 'showExpressionList';
      data.title = this.currentEntity.phaseCode + '电量表达式';
      data.isClosingDisabled = false;
      let showExpressionComponent = this.bladeService.createBlade(CalculateExpressionListComponent, data, false, null, this.currentEntity);
      this.bladeService.showBlade(showExpressionComponent, this.currentBlade);
    }
  }

  /**
   * 单选
   *
   * @param {any} event
   * @param {any} key
   *
   * @memberof FarmListComponent
   */
  onItemCheack(event: HTMLInputElement, key: Phase) {
    key.isChecked = event.checked;
  }

  /**
   * 全选/全不选
   *
   * @param {any} event
   *
   * @memberof FarmListComponent
   */
  onAllCheack(event: HTMLInputElement) {
    if (this.phases.length > 0) {
      for (let i = 0; i < this.phases.length; i++) {
        this.phases[i].isChecked = event.checked;
      }
    }
  }

  onSeletedChange(phase: Phase) {
    if (this.currentBlade.childrenCanDeactivate()) {
      this.showTurbineListBlade(phase);
    }
  }

  /**
   * 展开列表弹出层
   *
   * @param {Farm} farm
   *
   * @memberof FarmListComponent
   */
  // showTurbineListBlade(selectedPhase: Phase) {
  //     if (this.currentEntity != selectedPhase
  //         || this.bladeService.findBlade("phaseList") == undefined) {
  //         let data: BladeData = new BladeData();
  //         data.id = "phaseList";
  //         data.title = selectedPhase.phaseName + "风机列表";
  //         data.isClosingDisabled = false;
  //         let TurbineListBlade = this.bladeService.createBlade(TurbineListComponent, data, false, null, selectedPhase);
  //         this.bladeService.showBlade(TurbineListBlade, this.currentBlade).then(res => {
  //             if (res) {
  //                 this.currentEntity = selectedPhase;
  //             }
  //         });

  //     }
  // }

  showTurbineListBlade(selectedPhase: Phase) {
    if (this.currentEntity != selectedPhase || this.bladeService.findBlade('deviceList') == undefined) {
      let data: BladeData = new BladeData();
      data.id = 'deviceList';
      data.title = selectedPhase.phaseName + '设备列表';
      data.isClosingDisabled = false;
      let TurbineListBlade = this.bladeService.createBlade(DeviceListComponent, data, false, null, selectedPhase);
      this.bladeService.showBlade(TurbineListBlade, this.currentBlade).then(res => {
        if (res) {
          this.currentEntity = selectedPhase;
        }
      });
    }
  }


  /**
   * 获得选中项
   *
   * @returns {Setofkey[]}
   *
   * @memberof FarmListComponent
   */
  getSelected(): Phase[] {
    if (this.phases.length > 0) {
      let filter = this.phases.filter(ref => ref.isChecked)
      return filter == null ? [] : filter;
    }
    return [];
  }
}
